// 用户相关接口
import { request } from './httpBase';

// 微信小程序登录接口
export function wxlogin(code: string): Promise<{ msg: string; code: number; token: string }> {
  return request({
    url: '/wechatlogin/miniprogramLogin',
    method: 'GET',
    data: { code }
  }).then(res => {
    // 登录成功后，将token保存到本地存储
    const data = res as { msg: string; code: number; token: string };
    if (data.token) {
      wx.setStorageSync('token', data.token);
    }
    return data;
  });
}

// 获取用户信息接口
export function getInfo(): Promise<{ 
  nickName: string; 
  userName: string; 
  avatar: string;
  role: string;
}> {
  return new Promise((resolve, reject) => {
    request<{
      code: number;
      msg: string;
      roles: string[];
      user: {
        userId: string;
        nickName: string;
        userName: string;
        avatar: string;
      }
    }>({
      url: '/getInfo',
      method: 'GET'
    }).then(res => {
      // 提取用户角色
      const roles = res.roles || [];
      //const roleNames = roles.map(role => role.roleName);
      
      // 判断用户角色是否为admin或common
      const isValidRole = roles.some(role => role === 'admin' || role === 'common');
      
      if (isValidRole) {
        // 保存用户信息到本地
        const userInfo = {
          id: res.user.userId,
          nickName: res.user.nickName,
          userName: res.user.userName,
          avatar: res.user.avatar,
          role: roles.join(',')
        };
        
        wx.setStorageSync('userInfo', userInfo);
        resolve(userInfo);
      } else {
        // 角色不匹配，返回错误
        reject({
          msg: '用户角色不符合要求',
          code: 403
        });
      }
    }).catch(err => {
      // 请求失败，直接返回错误
      reject(err);
    });
  });
}

// 微信小程序注册新用户接口
export function wechatRegisterUser(params: {
  avatar: string;
  nickName: string;
  phone: string;
  phoneCode: string;
  wechatCode: string;
}): Promise<{ msg: string; code: number }> {
  return request({
    url: '/wechatlogin/miniprogramRegisterUser',
    method: 'POST',
    data: params
  });
}

// 发送手机验证码接口
export function sendSmsCode(phone: string): Promise<{ msg: string; code: number }> {
  return request({
    url: '/smslogin/sendSmsCode',
    method: 'POST',
    data: { 
      'phone': phone,
      'register' : true
    }
  });
}

// 退出登录接口
export function logout(): Promise<{ msg: string; code: number }> {
  return request({
    url: '/logout',
    method: 'POST'
  }).then(res => {
    return res as { msg: string; code: number };
  });
}

// 查询附近用户接口
export function getNearbyLocations(params: {
  longitude: number; // 中心点经度坐标
  latitude: number;  // 中心点纬度坐标
  distance?: number; // 搜索半径，单位为公里，默认值为10.0
}): Promise<{
  msg: string;
  code: number;
  data: Array<{
    userId: number;
    nickName: string;
    longitude: number;
    latitude: number;
  }>;
}> {
  return request({
    url: '/userlocation/nearby',
    method: 'GET',
    data: params
  });
}